class TemperatureSensorModule {
  constructor(deviceId) {
    this.topic = 'device/temperature'; // 温度数据发布主题
    this.minTemperature = 20; // 最低温度（摄氏度）
    this.maxTemperature = 30; // 最高温度（摄氏度）
    this.interval = 5000; // 发送间隔（毫秒）
    this.timer = null; // 定时器引用
    this.currentTemperature = 0; // 当前温度
    this.deviceId = deviceId;
  }

  // 初始化温度传感器模块
  async init(mqttConnector) {
    this.mqttConnector = mqttConnector;
    console.log('温度传感器模块已初始化');
    this.generateInitialTemperature();
  }

  // 生成初始温度
  generateInitialTemperature() {
    this.currentTemperature = parseFloat(
      (Math.random() * (this.maxTemperature - this.minTemperature) + this.minTemperature).toFixed(2)
    );
  }

  // 生成波动的温度值
  generateFluctuatedTemperature() {
    // 随机波动范围为±0.5℃
    const fluctuation = (Math.random() - 0.5) * 1;
    let newTemperature = this.currentTemperature + fluctuation;

    // 确保温度在范围内
    if (newTemperature < this.minTemperature) {
      newTemperature = this.minTemperature;
    } else if (newTemperature > this.maxTemperature) {
      newTemperature = this.maxTemperature;
    }

    this.currentTemperature = parseFloat(newTemperature.toFixed(2));
    return this.currentTemperature;
  }

  // 开始发送温度数据
  startSending() {
    if (this.timer) {
      console.log('温度数据发送已在运行中');
      return;
    }

    console.log('开始发送温度数据');
    this.sendTemperature(); // 立即发送一次
    this.timer = setInterval(() => {
      this.sendTemperature();
    }, this.interval);
  }

  // 发送温度数据
  async sendTemperature() {
    const temperature = this.generateFluctuatedTemperature();
    const temperatureMessage = {
      deviceId: this.deviceId,
      timestamp: Date.now(),
      type: 'sensor-data',
      data: {
        value: temperature+"",
        unit: '°C',
        status: 'normal'
      }
    };
    await this.mqttConnector.publish(this.topic, JSON.stringify(temperatureMessage));
  }

  // 停止发送温度数据
  stopSending() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
      console.log('停止发送温度数据');
    }
  }

  // 设置温度范围
  setTemperatureRange(min, max) {
    this.minTemperature = min;
    this.maxTemperature = max;
    console.log(`温度范围已设置: ${min}℃ - ${max}℃`);
  }

  // 设置发送间隔
  setInterval(interval) {
    this.interval = interval;
    console.log(`发送间隔已设置: ${interval}ms`);

    // 如果正在发送，则重新启动定时器
    if (this.timer) {
      this.stopSending();
      this.startSending();
    }
  }
}

module.exports = TemperatureSensorModule;